package com.xianguo.datacenter.download.Thread;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.xianguo.datacenter.download.Thread.Download.DownloadState;

public class DownloadUtil implements ServletContextListener {
	public static List<Download> downloadList = new ArrayList<Download>();//正在下载列表
	public static List<Download> downloadTempList = new ArrayList<Download>();//下载缓冲列表
	public static String vcodeState;
	private int downloadThreadCount = 2;//最多同时下载个数

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("下载控制核心线程控制启动");
		new Thread(new downloadCommonControl()).start();
	}
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		
	}
	
	public class downloadCommonControl implements Runnable{//下载核心控制器
		
		@Override
		public void run() {
			try {	
				while(true){
						Iterator<Download> downloadListiterator = downloadList.iterator();
						while(downloadListiterator.hasNext()){//循环下载列表
							Download item = downloadListiterator.next();
							if(item.getDownloadState()==DownloadState.SUSPEND){//找到已经暂停下载的线程
								downloadListiterator.remove();
								downloadTempList.add(item);
							}
						}
						Iterator<Download> downloadTempListiterator = downloadTempList.iterator();
						while(downloadTempListiterator.hasNext()){//循环缓冲区
							Download item = downloadTempListiterator.next();
							if(downloadList.size() < downloadThreadCount && downloadTempList.size() > 0){
								if(item.getDownloadState()==DownloadState.DOWNLOADING||item.getDownloadState()==DownloadState.CONTINUE){//处于下载状态和继续状态的才启动下载
									DownloadHttpThread download = (DownloadHttpThread)item;//拿到列表第一个等待任务
									downloadList.add(download);//添加到正在下载列表
									downloadTempListiterator.remove();//从缓冲区删除掉
									if(((DownloadHttpThread)item).getIsOneStart() != 1){//如果线程还没启动
										new Thread(download).start();//启动下载
										download.setDownloadState(DownloadState.DOWNLOADING);
									}else if(item.getDownloadState()==DownloadState.CONTINUE){//如果线程处于等待继续的状态
										download.setDownloadState(DownloadState.DOWNLOADING);//如果已经启动线程状态改为下载中
									}
								}
							}
						}
					Thread.sleep(3*1000);	
				}
			} catch (InterruptedException e) {
				System.out.println("核心控制器休眠出错");
			}
		}
	}
	
	//新建一个下载HTTP下载
	public static DownloadHttpThread addHttpDownload(String path,String fileName,String url,String cookie){
		DownloadHttpThread downloadThread = new DownloadHttpThread();
		downloadThread.setPath(path);
		downloadThread.setFileName(fileName);
		downloadThread.setUrl(url);
		downloadThread.setCookie(cookie);
		downloadThread.setDownloadState(DownloadState.CONTINUE);
		downloadThread.setUID(UUID.randomUUID().toString());
		downloadTempList.add(downloadThread);
		return downloadThread;
	}
	//新建一个百度云下载
	public static Map<String, String> addBaiDuYunDownload(String path,String url,String webPath){
		try {
			DownloadBaidDuYunThread downloadThread = new DownloadBaidDuYunThread();
			downloadThread.setPath(path);
			downloadThread.setUrl(url);
			downloadThread.setWebPath(webPath);
			downloadList.add(downloadThread);
			Thread thread = new Thread(downloadThread);
			thread.start();
			Map<String, String> map = new HashMap<String, String>();
			while(true){
				if(downloadThread.getvCodeState()!=null && !downloadThread.getvCodeState().equals("")){
					map.put("VCodeState", downloadThread.getvCodeState());
					map.put("VCodePath", downloadThread.getvCodePath());
					map.put("UID", downloadThread.getUID());
					break;
				}
				Thread.sleep(1000);
			}
			return map;
		} catch (InterruptedException e) {
			System.out.println("新建百度云下载失败");
			return null;
		}
	}
	//删除一个正在下载的线程
	public static void removeDownloadThread(String UID){//加上线程锁以免size混乱
		Iterator<Download> iterator = downloadList.iterator();
		while (iterator.hasNext()) {
			Download download = iterator.next();
			if (UID.equals(download.getUID())) {
				iterator.remove();
			}
		}
	}
	
	//删除一个缓冲区的下载线程
	public static void removeTempDownloadThread(String UID){//加上线程锁以免size混乱
		Iterator<Download> iterator = downloadTempList.iterator();
		while (iterator.hasNext()) {
			Download download = iterator.next();
			if (UID.equals(download.getUID())) {
				iterator.remove();
			}
		}
	}
	
	//为一个百度云线程写入验证码
	public static Map<String,String> setBaiDuYunVCode(String UID,String VCode){
		try {
			Map<String, String> map = new HashMap<String, String>();
			vcodeState = "";
			for(Download item : downloadList){
				if(item.getUID().equals(UID)){
					DownloadBaidDuYunThread downloadBaiDuYun = (DownloadBaidDuYunThread)item;
					downloadBaiDuYun.setvCode(VCode);
					while(true){
						if(vcodeState.equals("1")){
							map.put("VCodeState", downloadBaiDuYun.getvCodeState());
							map.put("VCodePath", downloadBaiDuYun.getvCodePath());
							map.put("UID", downloadBaiDuYun.getUID());
							break;
						}
						Thread.sleep(1000);
					}
					break;
				}
			}
			return map;
			
		} catch (InterruptedException e) {
			System.out.println("验证码写入出错");
			return null;
		}
	}
	
	//更改下载状态
	public  static void changeDownloadState(DownloadState isDownloading,String UID){
		for(Download item : downloadList){
			if(item.getUID().equals(UID)){
				item.setDownloadState(isDownloading);
			}
		}
		for(Download item : downloadTempList){
			if(item.getUID().equals(UID)){
				item.setDownloadState(isDownloading);
			}
		}
	}
}
